﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using StringDefs.Common;
using StringDefs.Web;

namespace StringDefs.SocialNetworking
{
    public static class Twitter
    {
        /// <summary>
        /// Gets the profile image URL for the user
        /// </summary>
        /// <param name="user">Twitter User ID</param>
        /// <returns>The twitter profile pic of the user whose user id is given</returns>
        public static string GetProfilePicImage(string user)
        {
            try
            {
                Stream webStream = new WebClient().OpenRead("http://twitter.com/" + user);
                StreamReader webReader = new StreamReader(webStream);
                string totalContent = webReader.ReadToEnd();
                webReader.Close();
                return totalContent.ExtractHyperlinks().First(c => c.ToLower().Contains("_bigger."));
            }
            catch
            {
                return "default_profile_0_bigger.jpg";
            }
        }

        /// <summary>
        /// Gets the latest tweet of the user whose user ID is given
        /// </summary>
        /// <param name="user">Twitter User ID of the person</param>
        /// <returns>The latest tweet as a string</returns>
        public static string GetLatestTweet(string user)
        {

            string tag = "<span class=" + "entry-content".Quote() + ">";
            string url = "http://twitter.com/" + user;
            WebClient wc = new WebClient();
            Stream webStream = wc.OpenRead(url);
            StreamReader sr = new StreamReader(webStream);
            string total = sr.ReadToEnd();
            sr.Close();
            string[] tokens = total.Split(new string[] { tag }, StringSplitOptions.RemoveEmptyEntries);
            string latestTweet = tokens[1].StripTags();
            latestTweet = latestTweet.Substring(0, latestTweet.IndexOf("via"))
                .Replace("\n", string.Empty).Replace("  ", " ").Trim();
            return latestTweet;
        }
    }
}
